package com.example.Arithmetic.Lettcode;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 日期：2024/1/3
 * 时间：10:47
 * 描述：组合总和，看有多少种组合等于目标target，回溯思想,不能重复使用
 */
public class E01Lettcode40 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> list = new ArrayList<>();
        dfs(0, candidates, target, new boolean[candidates.length], list, new LinkedList<>());
        return list;
    }

    private void dfs(int start, int[] candidates, int target, boolean[] booleans, List<List<Integer>> list, LinkedList<Integer> stack) {
        if (target == 0) {
            list.add(new ArrayList<>(stack));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            int candidate = candidates[i];
//            剪枝,小于目标值没有循环必要了
            if (target < candidate) {
                continue;
            }
            if (i > 0 && candidate == candidates[i - 1] && !booleans[i-1]) {
                continue;
            }
            stack.push(candidate);
            booleans[i]=true;
            dfs(i + 1, candidates, target - candidate, booleans, list, stack);
            stack.pop();
            booleans[i]=false;
        }
    }

    @Test
    public void test() {
        int[] candidates = {10, 1, 2, 7, 6, 1, 5};
        List<List<Integer>> lists = combinationSum(candidates, 8);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}

